<template>
    <view>
        <u-popup @close="closePopup" :closeOnClickOverlay="true" round="30rpx" :show="popupShow">
            <view class="popup ai-create">
                <view class="mask-loading" v-if="writing">
                    <u-loading-icon text="文案生成中..." :vertical="true"></u-loading-icon>
                </view>
                <view class="title-wrap u-border-bottom">
                    <view></view>
                    <view class="title">AI写文案</view>
                    <view @tap="closePopup" class="right">
                        <u-icon name="close"></u-icon>
                    </view>
                </view>
                <view class="tabs" v-if="topicList.length > 0">
                  <u-tabs
                      :list="topicList"
                      :value="topicCurrent"
                      lineColor="#ea4679"
                      keyName="title"
                      @change="topicChange"
                  ></u-tabs>
                </view>
                <view class="content">
                    <view class="themes">
                        <view class="label">选择模型</view>
                        <view class="list">
                            <view
                                @tap="selectModel(item)"
                                class="item u-line-1"
                                :class="{active: activeModel && activeModel.id === item.id}"
                                v-for="(item, index) in modelList"
                                :key="index"
                            >
                                {{item.title}}
                            </view>
                        </view>
                    </view>
                    <view class="form" v-if="activeModel">
                        <u-form
                            ref="uForm"
                            labelPosition="top"
                            labelWidth="auto"
                            :model="aiForm"
                        >
                            <view class="item">
                                <u-form-item :borderBottom="false" label="输入主题">
                                    <view style="width: 100%; margin-top: 30rpx;">
                                      <input
                                          class="input"
                                          :placeholder="activeModel.hint || '请输入主题'"
                                          @input="promptInput"
                                          maxlength="500"
                                          :value="aiForm.prompt"
                                      />
                                    </view>
                                </u-form-item>
                            </view>
                        </u-form>
                    </view>
                    <view class="tips" v-if="activeModel && activeModel.tips && activeModel.tips.length > 0">
                      <view class="title">参考内容</view>
                      <view class="list">
                        <view
                            class="item"
                            v-for="(item, index) in activeModel.tips"
                            :key="index"
                            @tap="setPrompt(item)"
                            @longtap="copyText(item)"
                        >
                          {{item}}
                        </view>
                      </view>
                    </view>
                </view>
                <view class="footer">
                    <button @tap="aiWrite" shape="circle" type="primary">生成文案</button>
                </view>
            </view>
        </u-popup>
    </view>
</template>

<script>
export default {
  data() {
    return {
      popupShow: false,
      writing: false,
      aiForm: {
        prompt: ''
      },
      topicList: [],
      topicCurrent: 0,
      activeModel: null,
      modelList: [],
      selectedModel: null,
      modelListParams: {
        page: 1,
        limit: 20,
        status: 'loadmore',
        isEmpty: false
      },
      aiResult: ''
    };
  },
  created() {
    this.getTopicList()

  },
  methods: {
    confirm() {
      this.$emit('confirm', this.aiResult);
      this.closePopup()
    },
    closePopup() {
      this.aiForm.prompt = ''
      this.popupShow = false;
    },
    selectModel(item) {
      this.activeModel = JSON.parse(JSON.stringify(item));
      this.aiForm.prompt = ''
    },
    topicChange(item) {
      this.topicCurrent = item.index;
      this.modelList = []
      this.modelListParams.page = 1
      this.getModelList()
    },
    getTopicList() {
      this.$util.request({
        url: '/ai/getWriteTopic',
        loading: false
      }).then(res => {
        this.topicList = res.data;
        this.getModelList()
      });
    },
    getModelList() {
      if (this.topicList.length === 0 || !this.topicList[this.topicCurrent]) {
        this.modelList = []
        return false
      }
      this.$util.request({
        url: '/ai/getWriteModelList',
        data: {
          topic_id: this.topicList[this.topicCurrent].id,
          page: this.modelListParams.page,
          limit: this.modelListParams.limit
        },
        loading: false
      }).then(res => {
        this.modelListParams.total = res.data.total;
        this.modelList = this.modelList.concat(res.data.list);
        if (res.data.total === 0) {
          this.modelListParams.isEmpty = true
        }
        this.modelListParams.status = this.modelList.length < res.data.total ? 'loadmore' : 'nomore';
        if (this.modelListParams.page === 1 && this.modelList.length > 0) {
          this.selectModel(this.modelList[0])
        } else {
          this.activeModel = null
        }
      });
    },
    promptInput(e) {
      this.aiForm.prompt = e.detail.value
    },
    setPrompt(text) {
      this.aiForm.prompt = text
    },
    copyText(text) {
      const that = this;
      uni.setClipboardData({
        data: text,
        success: function () {
          that.$util.message('已复制')
        }
      });
    },
    aiWrite() {
      if (!this.activeModel) {
        this.$util.message('请先选择模型')
        return
      }
      if (!this.aiForm.prompt) {
        this.$util.message('请输入')
        return
      }
      this.writing = true;
      this.$util.request({
        url: '/ai/makeText',
        data: {
          model_id: this.activeModel.id,
          prompt: this.aiForm.prompt
        },
        loading: false
      }).then(res => {
        this.writing = false;
        if (res.data) {
          this.aiResult = res.data
              .replace(/[，,！!。；;：:—()（）“”《》、?？]/g, '\n')
              .split('\n')
              .filter(item => {
                return item !== '';
              })
              .join('\n');
          this.confirm()
        }
      }).catch(() => {
        this.writing = false;
      })
    }
  }
}
</script>
<style>
@import './aiWrite.css';
</style>
